import React, { useState, useEffect } from 'react';
import { Layout, Tree, Typography, Spin, Alert, Empty } from 'antd';
import { FolderOutlined, FileTextOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import '../../styles/UserGuide.css';

const { Sider, Content } = Layout;
const { Title } = Typography;

const UserGuide = () => {
  const [treeData, setTreeData] = useState([]);
  const [selectedDoc, setSelectedDoc] = useState(null);
  const [docContent, setDocContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 模拟文档数据（实际项目中应该从API获取）
  const mockDocs = {
    'development-guide.md': {
      title: '开发指南',
      path: '/docs/development-guide.md'
    },
    'api-reference.md': {
      title: 'API 参考',
      path: '/docs/api-reference.md'
    },
    'user-guide.md': {
      title: '用户使用指南',
      path: '/docs/user-guide.md'
    },
    'deployment-guide.md': {
      title: '部署指南',
      path: '/docs/deployment-guide.md'
    },
    'troubleshooting.md': {
      title: '故障排除',
      path: '/docs/troubleshooting.md'
    }
  };

  // 初始化文档树
  useEffect(() => {
    const generateTreeData = () => {
      const tree = [
        {
          title: '📚 使用指南',
          key: 'user-guide',
          icon: <FolderOutlined />,
          children: [
            {
              title: '用户使用指南',
              key: 'user-guide.md',
              icon: <FileTextOutlined />,
              isLeaf: true
            }
          ]
        },
        {
          title: '🔧 开发文档',
          key: 'development',
          icon: <FolderOutlined />,
          children: [
            {
              title: '开发指南',
              key: 'development-guide.md',
              icon: <FileTextOutlined />,
              isLeaf: true
            },
            {
              title: 'API 参考',
              key: 'api-reference.md',
              icon: <FileTextOutlined />,
              isLeaf: true
            }
          ]
        },
        {
          title: '🚀 部署运维',
          key: 'deployment',
          icon: <FolderOutlined />,
          children: [
            {
              title: '部署指南',
              key: 'deployment-guide.md',
              icon: <FileTextOutlined />,
              isLeaf: true
            },
            {
              title: '故障排除',
              key: 'troubleshooting.md',
              icon: <FileTextOutlined />,
              isLeaf: true
            }
          ]
        }
      ];
      setTreeData(tree);
    };

    generateTreeData();
  }, []);

  // 加载文档内容
  const loadDocContent = async (docKey) => {
    if (!mockDocs[docKey]) return;

    setLoading(true);
    setError(null);

    try {
      // 在实际项目中，这里应该是API调用
      // const response = await fetch(`/api/docs/${docKey}`);
      // const content = await response.text();
      
      // 模拟加载延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟从本地文件读取内容
      const response = await fetch(`/docs/${docKey}`);
      if (response.ok) {
        const content = await response.text();
        setDocContent(content);
        setSelectedDoc({
          key: docKey,
          title: mockDocs[docKey].title
        });
      } else {
        throw new Error('文档加载失败');
      }
    } catch (err) {
      console.error('加载文档失败:', err);
      setError('文档加载失败，请稍后重试');
      // 设置默认内容
      setDocContent(`# ${mockDocs[docKey].title}\n\n文档内容加载中...\n\n请确保文档文件存在于 \`/docs\` 目录下。`);
      setSelectedDoc({
        key: docKey,
        title: mockDocs[docKey].title
      });
    } finally {
      setLoading(false);
    }
  };

  // 处理树节点选择
  const handleTreeSelect = (selectedKeys) => {
    if (selectedKeys.length > 0) {
      const key = selectedKeys[0];
      if (key.endsWith('.md')) {
        loadDocContent(key);
      }
    }
  };

  // 默认加载第一个文档
  useEffect(() => {
    if (treeData.length > 0 && !selectedDoc) {
      loadDocContent('user-guide.md');
    }
  }, [treeData, selectedDoc]);

  return (
    <div className="user-guide-container">
      <Layout className="user-guide-layout">
        <Sider 
          // theme="light"
          // width={300} 
          className="user-guide-sider"
        >
          <div className="guide-sider-header">
            <Title level={4}>📖 文档导航</Title>
          </div>
          <div className="guide-tree-container">
            <Tree
              treeData={treeData}
              onSelect={handleTreeSelect}
              defaultExpandAll
              selectedKeys={selectedDoc ? [selectedDoc.key] : []}
              className="guide-tree"
            />
          </div>
        </Sider>
        
        <Content className="user-guide-content">
          {loading ? (
            <div className="guide-loading">
              <Spin size="large" />
              <p>加载文档中...</p>
            </div>
          ) : error ? (
            <Alert
              message="加载失败"
              description={error}
              type="error"
              showIcon
              className="guide-error"
            />
          ) : selectedDoc ? (
            <div className="guide-doc-container">
              <div className="guide-doc-content">
                <ReactMarkdown 
                  remarkPlugins={[remarkGfm]}
                  components={{
                    // 自定义代码块样式
                    code({node, inline, className, children, ...props}) {
                      const match = /language-(\w+)/.exec(className || '');
                      return !inline && match ? (
                        <pre className="code-block">
                          <code className={className} {...props}>
                            {children}
                          </code>
                        </pre>
                      ) : (
                        <code className="inline-code" {...props}>
                          {children}
                        </code>
                      );
                    },
                    // 自定义表格样式
                    table({children}) {
                      return <table className="markdown-table">{children}</table>;
                    },
                    // 自定义链接样式
                    a({children, href}) {
                      return (
                        <a href={href} target="_blank" rel="noopener noreferrer" className="markdown-link">
                          {children}
                        </a>
                      );
                    }
                  }}
                >
                  {docContent}
                </ReactMarkdown>
              </div>
            </div>
          ) : (
            <div className="guide-empty">
              <Empty
                description="请从左侧选择要查看的文档"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            </div>
          )}
        </Content>
      </Layout>
    </div>
  );
};

export default UserGuide;